package com.epam.player.desktop.view;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.InputStream;
import java.sql.Time;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import javazoom.jl.player.Player;

import com.epam.player.desktop.events.button.ButtonDownloadActionEvent;
import com.epam.player.desktop.logic.MP3PlayerManager;
import com.epam.player.vkapi.exceptions.TemporarilyUnavailableServiceException;
import com.epam.player.vkapi.model.Song;
import com.epam.player.vkapi.music.MusicManager;

public class MainForm {

	static int indexList = 0;
	static Timer timerPlay = new Timer();
	static Player player = null;
	static InputStream inputStream;
	static MusicManager musicManager = new MusicManager();
	static List<Song> songs;
	static boolean flagClickSearch = false;
	static String serachQuery;
	static Timer mainTimer = new Timer();
	private JTextField textField;
	private boolean flagMyMusic = false;
	private JList list;
	private JFrame frame;
	private JLabel labelTimer_1;
	private JScrollPane scrollPane_1;
	private JLabel lblTimel_1;
	private JLabel lblSearch_1;
	private JButton buttonSearch_1;
	private JButton buttonDownload_1;
	private JButton btnAddToMy_1;
	private JLabel labelStatusDownload_1;
	private JProgressBar progressBar_1;
	private JButton btnStop_1;
	MP3PlayerManager playerManager = new MP3PlayerManager();
	JLabel lblLblplaysong;

	/**
	 * @wbp.parser.entryPoint
	 */
	public void start() {
		frame = new JFrame("VKPlayer");
		frame.setResizable(false);
		buttonSearch_1 = new JButton("Search");
		try {
			songs = musicManager.getPopularSongs(0);
		} catch (TemporarilyUnavailableServiceException e2) {
			e2.printStackTrace();
		}
		list = new JList(songs.toArray());
		list.setForeground(new Color(0, 0, 0));

		list.setVisibleRowCount(15);
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list.setLayoutOrientation(JList.VERTICAL);
		scrollPane_1 = new JScrollPane(list);

		textField = new JTextField();
		textField.setColumns(10);
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				if (e.getKeyChar() == '\n') {
					buttonSearch_1.doClick();
				}
			}
		});
		buttonDownload_1 = new JButton("Download");

		btnAddToMy_1 = new JButton("Add to My");
		btnAddToMy_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					musicManager.addToMyListSongs(songs.get(list.getSelectedIndex()));
					songs.remove(list.getSelectedIndex());
					list.setListData(songs.toArray());
				} catch (TemporarilyUnavailableServiceException e) {
					e.printStackTrace();
				}
			}
		});
		btnAddToMy_1.setVisible(false);
		buttonDownload_1.setVisible(false);
		lblTimel_1 = new JLabel("");
		lblTimel_1.setForeground(Color.BLUE);

		progressBar_1 = new JProgressBar();
		progressBar_1.setForeground(new Color(0, 100, 0));
		labelStatusDownload_1 = new JLabel("");
		labelStatusDownload_1.setForeground(new Color(0, 51, 255));

		scrollPane_1.getVerticalScrollBar().addAdjustmentListener(
				new AdjustmentListener() {
					@Override
					public void adjustmentValueChanged(AdjustmentEvent e) {
						if (e.getAdjustable().getValue() >= (e.getAdjustable()
								.getMaximum() - 300)) {
							if (flagClickSearch == false
									&& flagMyMusic == false) {
								setPopularMusic(list);
							} else if (flagClickSearch == true
									&& flagMyMusic == false) {
								List<Song> listSongs = null;
								try {
									listSongs = musicManager.searchSongs(
											serachQuery, songs.size());
								} catch (TemporarilyUnavailableServiceException e1) {
									e1.printStackTrace();
								}
								if (listSongs != null) {
									songs.addAll(listSongs);
									list.setListData(songs.toArray());
								}

							}

						}

					}

					private void setPopularMusic(final JList jList) {
						int size = songs.size();
						List<Song> list = null;
						try {
							list = musicManager.getPopularSongs(size);
						} catch (TemporarilyUnavailableServiceException e) {
							e.printStackTrace();
						}
						if (list != null) {
							songs.addAll(list);
							jList.setListData(songs.toArray());
						}

					}
				});

		buttonSearch_1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				serachQuery = textField.getText();
				try {
					songs = musicManager.searchSongs(serachQuery, 0);
				} catch (TemporarilyUnavailableServiceException e1) {
					e1.printStackTrace();
				}
				flagClickSearch = true;
				flagMyMusic = false;
				list.setListData(songs.toArray());
			}
		});

		labelTimer_1 = new JLabel("");
		labelTimer_1.setFont(new Font("Tahoma", Font.BOLD, 14));
		labelTimer_1.setForeground(new Color(0, 100, 0));

		progressBar_1.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent arg0) {
				lblTimel_1.setText(progressBar_1.getValue() + "%");
			}
		});
		
		buttonDownload_1.addActionListener(new ButtonDownloadActionEvent(list,
				labelStatusDownload_1, progressBar_1, buttonDownload_1));

		lblSearch_1 = new JLabel("Search:");

		JMenuItem mntmPopular = new JMenuItem("Popular");
		mntmPopular.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				songs.clear();
				flagClickSearch = false;
				flagMyMusic = false;
				try {
					songs = musicManager.getPopularSongs(0);
				} catch (TemporarilyUnavailableServiceException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				list.setListData(songs.toArray());
			}
		});
		
		JMenuItem mntmMyMusic = new JMenuItem("My Music");
		mntmMyMusic.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				songs.clear();
				try {
					songs = musicManager.getMyList();
				} catch (TemporarilyUnavailableServiceException e1) {
					e1.printStackTrace();
				}
				flagMyMusic = true;
				list.setListData(songs.toArray());
			}
		});

		// frame.pack();
		frame.setSize(462, 457);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		final JPopupMenu popup = new JPopupMenu();
		JMenuItem menuItem = new JMenuItem("Download");
		menuItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				buttonDownload_1.doClick();
			}
		});
		final JMenuItem addToMyList = new JMenuItem("Add to My List");
		addToMyList.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				btnAddToMy_1.doClick();
			}
		});
		popup.add(addToMyList);
		popup.add(menuItem);

		list.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(final MouseEvent e) {
				if (SwingUtilities.isLeftMouseButton(e)
						&& e.getClickCount() == 2) {
					int indexSelectedList = list.locationToIndex(e.getPoint());
					ListModel dlm = list.getModel();
					Song song = (Song) dlm.getElementAt(indexSelectedList);
					list.ensureIndexIsVisible(indexSelectedList);
					play(song);

					if (labelStatusDownload_1.getText().indexOf(
							"Download completed") != -1
							|| labelStatusDownload_1.getText().indexOf(
									"At first") != -1) {
						labelStatusDownload_1.setText("");
						progressBar_1.setValue(0);
						lblTimel_1.setText("");
					}
				}
				if (SwingUtilities.isRightMouseButton(e)) {
					int indexSelectedList = list.locationToIndex(e.getPoint());
					list.setSelectedIndex(indexSelectedList);

					if (flagMyMusic == true) {
						popup.remove(addToMyList);
					} else {
						popup.add(addToMyList);
					}
					popup.show(e.getComponent(), e.getX(), e.getY());
				}

			}
		});

		btnStop_1 = new JButton("Stop");
		btnStop_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				playerManager.stop();

			}
		});
		lblLblplaysong = new JLabel("");
		initGroupLayout(buttonSearch_1, scrollPane_1, buttonDownload_1,
				btnAddToMy_1, lblTimel_1, progressBar_1, labelStatusDownload_1,
				labelTimer_1, lblSearch_1, btnStop_1, lblLblplaysong);

		JMenuBar menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);
		JMenu mnList = new JMenu("List");
		menuBar.add(mnList);
		mnList.add(mntmPopular);
		mnList.add(mntmMyMusic);

		mainTimer.schedule(new TimerTask() {
			Time time;

			@SuppressWarnings("deprecation")
			@Override
			public void run() {
				time = new Time(playerManager.getCurrentPosition());
				int seconds = time.getSeconds();
				String result = time.getMinutes() + ":" + seconds;
				if (seconds < 10) {
					result = time.getMinutes() + ":0" + seconds;
				}
				labelTimer_1.setText(result);
				JScrollBar vertical = scrollPane_1.getVerticalScrollBar();
				if (playerManager.isComplete()) {
					int index = list.getSelectedIndex();
					++index;
					if (songs.size() > index) {
						list.setSelectedIndex(index);
						vertical.setValue(vertical.getValue() + 15);
						scrollPane_1.setVerticalScrollBar(vertical);
						play(songs.get(index));
					} else {
						list.setSelectedIndex(0);
						vertical.setValue(0);
						scrollPane_1.setVerticalScrollBar(vertical);
						play(songs.get(0));
					}
				}
			}
		}, 0, 500);

	}

	private void initGroupLayout(JButton buttonSearch, JScrollPane scrollPane,
			JButton buttonDownload, final JButton btnAddToMy,
			final JLabel lblTimel, final JProgressBar progressBar,
			final JLabel labelStatusDownload, final JLabel labelTimer,
			JLabel lblSearch, JButton btnStop, JLabel lblLblplaysong) {

		GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
		groupLayout
				.setHorizontalGroup(groupLayout
						.createParallelGroup(Alignment.TRAILING)
						.addGroup(
								Alignment.LEADING,
								groupLayout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												groupLayout
														.createParallelGroup(
																Alignment.LEADING)
														.addGroup(
																Alignment.TRAILING,
																groupLayout
																		.createParallelGroup(
																				Alignment.LEADING)
																		.addGroup(
																				groupLayout
																						.createSequentialGroup()
																						.addComponent(
																								labelStatusDownload_1,
																								GroupLayout.DEFAULT_SIZE,
																								317,
																								Short.MAX_VALUE)
																						.addPreferredGap(
																								ComponentPlacement.RELATED)
																						.addComponent(
																								buttonDownload_1))
																		.addGroup(
																				groupLayout
																						.createSequentialGroup()
																						.addGap(6)
																						.addGroup(
																								groupLayout
																										.createParallelGroup(
																												Alignment.TRAILING,
																												false)
																										.addComponent(
																												lblTimel_1,
																												Alignment.LEADING,
																												GroupLayout.DEFAULT_SIZE,
																												GroupLayout.DEFAULT_SIZE,
																												Short.MAX_VALUE)
																										.addComponent(
																												lblSearch_1,
																												Alignment.LEADING,
																												GroupLayout.DEFAULT_SIZE,
																												GroupLayout.DEFAULT_SIZE,
																												Short.MAX_VALUE))
																						.addPreferredGap(
																								ComponentPlacement.RELATED)
																						.addGroup(
																								groupLayout
																										.createParallelGroup(
																												Alignment.LEADING)
																										.addGroup(
																												groupLayout
																														.createSequentialGroup()
																														.addComponent(
																																labelTimer_1,
																																GroupLayout.PREFERRED_SIZE,
																																40,
																																GroupLayout.PREFERRED_SIZE)
																														.addPreferredGap(
																																ComponentPlacement.RELATED)
																														.addComponent(
																																lblLblplaysong,
																																GroupLayout.DEFAULT_SIZE,
																																336,
																																Short.MAX_VALUE))
																										.addGroup(
																												groupLayout
																														.createSequentialGroup()
																														.addComponent(
																																textField,
																																GroupLayout.PREFERRED_SIZE,
																																109,
																																GroupLayout.PREFERRED_SIZE)
																														.addPreferredGap(
																																ComponentPlacement.RELATED)
																														.addComponent(
																																buttonSearch_1,
																																GroupLayout.PREFERRED_SIZE,
																																84,
																																GroupLayout.PREFERRED_SIZE)
																														.addPreferredGap(
																																ComponentPlacement.RELATED)
																														.addComponent(
																																btnStop_1)
																														.addPreferredGap(
																																ComponentPlacement.UNRELATED)
																														.addComponent(
																																btnAddToMy_1)))))
														.addGroup(
																groupLayout
																		.createParallelGroup(
																				Alignment.TRAILING,
																				false)
																		.addComponent(
																				progressBar_1,
																				Alignment.LEADING,
																				GroupLayout.DEFAULT_SIZE,
																				GroupLayout.DEFAULT_SIZE,
																				Short.MAX_VALUE)
																		.addComponent(
																				scrollPane_1,
																				Alignment.LEADING,
																				GroupLayout.DEFAULT_SIZE,
																				431,
																				Short.MAX_VALUE)))
										.addGap(175)));
		groupLayout
				.setVerticalGroup(groupLayout
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								groupLayout
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(scrollPane_1,
												GroupLayout.PREFERRED_SIZE,
												242, GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												ComponentPlacement.UNRELATED)
										.addGroup(
												groupLayout
														.createParallelGroup(
																Alignment.BASELINE)
														.addComponent(
																lblSearch_1)
														.addComponent(
																textField,
																GroupLayout.PREFERRED_SIZE,
																GroupLayout.DEFAULT_SIZE,
																GroupLayout.PREFERRED_SIZE)
														.addComponent(
																buttonSearch_1)
														.addComponent(btnStop_1)
														.addComponent(
																btnAddToMy_1))
										.addPreferredGap(
												ComponentPlacement.RELATED)
										.addGroup(
												groupLayout
														.createParallelGroup(
																Alignment.LEADING)
														.addComponent(
																lblLblplaysong,
																GroupLayout.DEFAULT_SIZE,
																24,
																Short.MAX_VALUE)
														.addComponent(
																labelTimer_1,
																Alignment.TRAILING,
																GroupLayout.DEFAULT_SIZE,
																24,
																Short.MAX_VALUE)
														.addComponent(
																lblTimel_1,
																Alignment.TRAILING))
										.addPreferredGap(
												ComponentPlacement.RELATED)
										.addComponent(progressBar_1,
												GroupLayout.PREFERRED_SIZE, 27,
												GroupLayout.PREFERRED_SIZE)
										.addGap(17)
										.addGroup(
												groupLayout
														.createParallelGroup(
																Alignment.TRAILING)
														.addComponent(
																labelStatusDownload_1,
																GroupLayout.PREFERRED_SIZE,
																22,
																GroupLayout.PREFERRED_SIZE)
														.addComponent(
																buttonDownload_1))
										.addGap(18)));

		frame.getContentPane().setLayout(groupLayout);

	}

	private void play(final Song song) {
		playerManager.stop();
		playerManager.play(song);
		String playTitle = song.getAuthor() + "-" + song.getTitle();
		if (playTitle.length() > 50) {
			lblLblplaysong.setText(playTitle.substring(indexList, 50) + "...");
		} else {
			lblLblplaysong.setText(playTitle);
		}

	}
}
